import { HOME_URL } from '@/common/constants/global'
import { useAuthStore } from '@/stores/auth'

/**
 * 获取面包屑
 * @param {Route} route 当前页面路由
 * @param {Boolean} homeAffix 是否固定首页 默认true
 * @returns {Array} 面包屑
 */
export function useBreadcrum(route, homeAffix = true) {
  const menuTree = useAuthStore().menuTree

  // 递归查找当前路由对应的菜单项及其所有父级
  function findPath(menus, path, parents = []) {
    for (const menu of menus) {
      // 当前路径匹配
      if (menu.path === path) {
        return [...parents, menu]
      }
      // 有子菜单则递归查找
      if (menu.children?.length) {
        const result = findPath(menu.children, path, [...parents, menu])
        if (result) {
          return result
        }
      }
    }
    return []
  }

  // 获取当前路由的完整路径
  const currentPath = route.path
  // 构建面包屑
  const matchedPath = findPath(menuTree, currentPath)

  // 如果固定首页，且 matchedPath 中不包含首页时，则将首页添加到面包屑中
  if (homeAffix && matchedPath.length && !matchedPath.some((item) => item.path === HOME_URL)) {
    const homePage = menuTree.find((item) => item.path === HOME_URL)
    matchedPath.unshift(homePage)
  }

  // 生成面包屑
  let breadcrumbs = matchedPath || []
  return breadcrumbs
}
